

<template>
  <!-- 基本信息 -->
  <div class="mainTitle">
    <h2>基本信息</h2>
    <span class="tips">必填项，须确保所填信息真实、准确、完整。信息一经提交，不可随意修改。</span>
    <span class="edit" @click="toggleEdit('basic')" v-if="!editMode.basic">编辑</span>
    <div v-if="editMode.basic" class="edit-actions">
      <span class="save" @click="saveBasicInfo">保存</span>
      <span class="cancel" @click="cancelEdit('basic')">取消</span>
    </div>
  </div>

  <!-- 基本信息展示/编辑 -->
  <div class="info-content" v-if="!editMode.basic">
    <div class="info-row">
      <div class="info-item">
        <label>昵称：</label>
        <span>{{ userInfo.nickname || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>国家/地区：</label>
        <span>{{ userInfo.country || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>证件类型：</label>
        <span>{{ getIdTypeText(userInfo.type) }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>证件号码：</label>
        <span>{{ userInfo.num || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>姓名：</label>
        <span>{{ userInfo.name || '未填写' }}</span>
      </div>

      <div class="info-item">
        <label>性别：</label>
        <span>{{ getSexText(userInfo.sex) }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>生日：</label>
        <span>{{ userInfo.birthday || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>现居省/市区：</label>
        <span>{{ userInfo.live || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>详细地址：</label>
        <span>{{ userInfo.detailed || '未填写' }}</span>
      </div>
    </div>

    <div class="info-row">
      <div class="info-item">
        <label>证件有效期开始：</label>
        <span>{{ userInfo.begin || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>证件有效期结束：</label>
        <span>{{ userInfo.end || '未填写' }}</span>
      </div>
      <div class="info-item"></div>
    </div>
  </div>

  <!-- 基本信息编辑表单 -->
  <div class="form-content" v-if="editMode.basic">
    <div class="form-row">
      <div class="form-item">
        <label>昵称 <span class="required">*</span></label>
        <input type="text" v-model="formData.nickname" placeholder="请输入昵称" />
      </div>
      <div class="form-item">
        <label>国家/地区 <span class="required">*</span></label>
        <select v-model="formData.country">
          <option value="">请选择国家/地区</option>
          <option value="中国">中国</option>
          <option value="美国">美国</option>
          <option value="英国">英国</option>
          <option value="其他">其他</option>
        </select>
      </div>
      <div class="form-item">
        <label>证件类型 <span class="required">*</span></label>
        <select v-model="formData.type">
          <option value="">请选择证件类型</option>
          <option value="1">身份证</option>
        </select>
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>证件号码 <span class="required">*</span></label>
        <input type="text" v-model="formData.num" placeholder="请输入证件号码" />
      </div>
      <div class="form-item">
        <label>姓名 <span class="required">*</span></label>
        <input type="text" v-model="formData.name" placeholder="请输入姓名" />
      </div>
      <div class="form-item">
        <label>性别 <span class="required">*</span></label>
        <select v-model="formData.sex">
          <option value="">请选择性别</option>
          <option value="1">男</option>
          <option value="2">女</option>
        </select>
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>生日 <span class="required">*</span></label>
        <input type="date" v-model="formData.birthday" />
      </div>
      <div class="form-item">
        <label>现居省/市区 <span class="required">*</span></label>
        <input type="text" v-model="formData.live" placeholder="请输入现居省/市区" />
      </div>
      <div class="form-item">
        <label>详细地址 <span class="required">*</span></label>
        <input type="text" v-model="formData.detailed" placeholder="请输入详细地址" />
      </div>
    </div>

    <div class="form-row">
      <div class="form-item">
        <label>证件有效期开始 <span class="required">*</span></label>
        <input type="date" v-model="formData.begin" />
      </div>
      <div class="form-item">
        <label>证件有效期结束 <span class="required">*</span></label>
        <input type="date" v-model="formData.end" />
      </div>
      <div class="form-item"></div>
    </div>
  </div>

  <!-- 账户安全 -->
  <div class="mainTitle">
    <h2>账户安全</h2>
    <span class="tips">必填项，须确保所填信息真实、准确、完整。信息一经提交，不可随意修改。</span>
    <span class="edit" @click="toggleEdit('security')" v-if="!editMode.security">编辑</span>
    <div v-if="editMode.security" class="edit-actions">
      <span class="save" @click="saveSecurityInfo">保存</span>
      <span class="cancel" @click="cancelEdit('security')">取消</span>
    </div>
  </div>

  <!-- 账户安全展示/编辑 -->
  <div class="info-content" v-if="!editMode.security">
    <div class="info-row">
      <div class="info-item">
        <label>头像：</label>
        <img :src="userInfo.avatar"  alt="userAvatar" class="avatar"
             @click="openPreview(0)" v-if="userInfo.avatar" />
        <span v-else>未上传</span>
      </div>
      <div class="info-item">
        <label>邮箱：</label>
        <span>{{ userInfo.email || '未填写' }}</span>
      </div>

      <div class="info-item">
        <label>手机号码：</label>
        <span>{{ userInfo.phone || '未填写' }}</span>
      </div>
    </div>
  </div>

  <!-- 账户安全编辑表单 -->
  <div class="form-content" v-if="editMode.security">
    <div class="form-row">
      <!-- 在账户安全部分的头像显示区域（约第125行） -->
      <div class="form-item avatar-upload-container">
        <label>头像</label>
        <div class="avatar-upload-wrapper">
          <div class="avatar-preview" :class="{ 'has-avatar': userInfo.avatar || formData.avatar }">
            <img
              v-if="userInfo.avatar || formData.avatar"
              :src="userInfo.avatar || formData.avatar"
              alt="头像"
              class="avatar-image"
            />
            <div v-else class="avatar-placeholder">
              <svg class="upload-icon" viewBox="0 0 24 24" width="24" height="24">
                <path fill="currentColor" d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
              </svg>
              <span>点击上传头像</span>
            </div>
            <div class="upload-overlay">
              <svg class="camera-icon" viewBox="0 0 24 24" width="20" height="20">
                <path fill="currentColor" d="M4,4H7L9,2H15L17,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9Z" />
              </svg>
              <span>更换头像</span>
            </div>
            <div class="upload-loading">
              <div class="loading-spinner"></div>
              <span>上传中...</span>
            </div>
          </div>
          <input
            type="file"
            accept="image/*"
            @change="handleAvatarChange"
            class="avatar-input"
            ref="avatarInput"
          />
        </div>
      </div>
      <div class="form-item">
        <label>邮箱 <span class="required">*</span></label>
        <input type="email" v-model="formData.email" placeholder="请输入邮箱" />
      </div>
      <div class="form-item">
        <label>手机号码 <span class="required">*</span></label>
        <input type="tel" v-model="formData.phone" placeholder="请输入手机号码" />
      </div>
    </div>
  </div>

  <!-- 紧急联系人 -->
  <div class="mainTitle">
    <h2>紧急联系人</h2>
    <span class="tips">必填项，须确保所填信息真实、准确、完整。</span>
    <span class="edit" @click="toggleEdit('emergency')" v-if="!editMode.emergency">编辑</span>
    <div v-if="editMode.emergency" class="edit-actions">
      <span class="save" @click="saveEmergencyInfo">保存</span>
      <span class="cancel" @click="cancelEdit('emergency')">取消</span>
    </div>
  </div>

  <!-- 紧急联系人展示/编辑 -->
  <div class="info-content" v-if="!editMode.emergency">
    <div class="info-row">
      <div class="info-item">
        <label>紧急联系人（姓名）：</label>
        <span>{{ userInfo.urgentName || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>紧急联系人（关系）：</label>
        <span>{{ userInfo.urgentRelationship || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>紧急联系人（电话）：</label>
        <span>{{ userInfo.urgentPhone || '未填写' }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>紧急联系人（详细地址）：</label>
        <span>{{ userInfo.urgentDetailed || '未填写' }}</span>
      </div>
    </div>
  </div>

  <!-- 紧急联系人编辑表单 -->
  <div class="form-content" v-if="editMode.emergency">
    <div class="form-row">
      <div class="form-item">
        <label>紧急联系人（姓名） <span class="required">*</span></label>
        <input type="text" v-model="formData.urgentName" placeholder="请输入紧急联系人姓名" />
      </div>
      <div class="form-item">
        <label>紧急联系人（关系） <span class="required">*</span></label>
        <select v-model="formData.urgentRelationship">
          <option value="">请选择关系</option>
          <option value="父亲">父亲</option>
          <option value="母亲">母亲</option>
          <option value="配偶">配偶</option>
          <option value="子女">子女</option>
          <option value="兄弟姐妹">兄弟姐妹</option>
          <option value="朋友">朋友</option>
          <option value="其他">其他</option>
        </select>
      </div>
      <div class="form-item">
        <label>紧急联系人（电话） <span class="required">*</span></label>
        <input type="tel" v-model="formData.urgentPhone" placeholder="请输入紧急联系人电话" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>紧急联系人（详细地址） <span class="required">*</span></label>
        <input type="text" v-model="formData.urgentDetailed" placeholder="请输入紧急联系人详细地址" />
      </div>
    </div>
  </div>

  <!-- 更多资料 -->
  <div class="mainTitle">
    <h2>更多资料</h2>
    <span class="tips">以下内容为选填项，完成可获得200上马积分。</span>
    <span class="edit" @click="toggleEdit('additional')" v-if="!editMode.additional">编辑</span>
    <div v-if="editMode.additional" class="edit-actions">
      <span class="save" @click="saveAdditionalInfo">保存</span>
      <span class="cancel" @click="cancelEdit('additional')">取消</span>
    </div>
  </div>

  <!-- 更多资料展示/编辑 -->
  <div class="info-content" v-if="!editMode.additional">
    <div class="info-row">
      <div class="info-item">
        <label>学历：</label>
        <span>{{ userInfo.qualification || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>血型：</label>
        <span>{{ userInfo.bloodType || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>行业：</label>
        <span>{{ userInfo.industry || '未填写' }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>年薪：</label>
        <span>{{ userInfo.annualSalary ? userInfo.annualSalary + '万' : '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>职业：</label>
        <span>{{ userInfo.occupation || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>身体状况：</label>
        <span>{{ userInfo.physicalCondition || '未填写' }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>参与跑步年数：</label>
        <span>{{ userInfo.runningYear ? userInfo.runningYear + '年' : '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>每周跑步次数：</label>
        <span>{{ userInfo.weeklyRunning ? userInfo.weeklyRunning + '次' : '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>每月跑步公里：</label>
        <span>{{ userInfo.monthlyRunning ? userInfo.monthlyRunning + '公里' : '未填写' }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>首次完成全马日期：</label>
        <span>{{ userInfo.firstTimeComplete || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>半马个人最好成绩：</label>
        <span>{{ userInfo.halfHorseDest || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>参加上马次数：</label>
        <span>{{ userInfo.participateFrequency ? userInfo.participateFrequency + '次' : '未填写' }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>穿着跑鞋品牌：</label>
        <span>{{ userInfo.runningShoeDrand || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>穿着服装品牌：</label>
        <span>{{ userInfo.clothingDrand || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>佩戴运动手表品牌：</label>
        <span>{{ userInfo.watchDrand || '未填写' }}</span>
      </div>
    </div>
    <div class="info-row">
      <div class="info-item">
        <label>使用跑步软件：</label>
        <span>{{ userInfo.runningApp || '未填写' }}</span>
      </div>
      <div class="info-item">
        <label>最爱喝运动饮料品牌：</label>
        <span>{{ userInfo.sportsDrink || '未填写' }}</span>
      </div>
      <div class="info-item"></div>
    </div>
  </div>

  <!-- 更多资料编辑表单 -->
  <div class="form-content" v-if="editMode.additional">
    <div class="form-row">
      <div class="form-item">
        <label>学历</label>
        <select v-model="formData.qualification">
          <option value="">请选择学历</option>
          <option value="小学">小学</option>
          <option value="初中">初中</option>
          <option value="高中">高中</option>
          <option value="大专">大专</option>
          <option value="本科">本科</option>
          <option value="硕士">硕士</option>
          <option value="博士">博士</option>
        </select>
      </div>
      <div class="form-item">
        <label>血型</label>
        <select v-model="formData.bloodType">
          <option value="">请选择血型</option>
          <option value="A型">A型</option>
          <option value="B型">B型</option>
          <option value="AB型">AB型</option>
          <option value="O型">O型</option>
          <option value="未知">未知</option>
        </select>
      </div>
      <div class="form-item">
        <label>行业</label>
        <input type="text" v-model="formData.industry" placeholder="请输入行业" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>年薪</label>
        <input type="number" v-model="formData.annualSalary" placeholder="请输入年薪（万）" />
      </div>
      <div class="form-item">
        <label>职业</label>
        <input type="text" v-model="formData.occupation" placeholder="请输入职业" />
      </div>
      <div class="form-item">
        <label>身体状况</label>
        <select v-model="formData.physicalCondition">
          <option value="">请选择身体状况</option>
          <option value="良好">良好</option>
          <option value="一般">一般</option>
          <option value="较差">较差</option>
        </select>
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>参与跑步年数</label>
        <input type="number" v-model="formData.runningYear" placeholder="请输入参与跑步年数" />
      </div>
      <div class="form-item">
        <label>每周跑步次数</label>
        <input type="number" v-model="formData.weeklyRunning" placeholder="请输入每周跑步次数" />
      </div>
      <div class="form-item">
        <label>每月跑步公里</label>
        <input type="number" v-model="formData.monthlyRunning" placeholder="请输入每月跑步公里" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>首次完成全马日期</label>
        <input type="date" v-model="formData.firstTimeComplete" />
      </div>
      <div class="form-item">
        <label>半马个人最好成绩</label>
        <input type="text" v-model="formData.halfHorseDest" placeholder="请输入半马个人最好成绩" />
      </div>
      <div class="form-item">
        <label>参加上马次数</label>
        <input type="number" v-model="formData.participateFrequency" placeholder="请输入参加上马次数" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>穿着跑鞋品牌</label>
        <input type="text" v-model="formData.runningShoeDrand" placeholder="请输入穿着跑鞋品牌" />
      </div>
      <div class="form-item">
        <label>穿着服装品牌</label>
        <input type="text" v-model="formData.clothingDrand" placeholder="请输入穿着服装品牌" />
      </div>
      <div class="form-item">
        <label>佩戴运动手表品牌</label>
        <input type="text" v-model="formData.watchDrand" placeholder="请输入佩戴运动手表品牌" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-item">
        <label>使用跑步软件</label>
        <input type="text" v-model="formData.runningApp" placeholder="请输入使用跑步软件" />
      </div>
      <div class="form-item">
        <label>最爱喝运动饮料品牌</label>
        <input type="text" v-model="formData.sportsDrink" placeholder="请输入最爱喝运动饮料品牌" />
      </div>
      <div class="form-item"></div>
    </div>
  </div>


  <ImagePreview
    v-model:visible="previewVisible"
    v-model:current-index="currentIndex"
    :images="[userInfo.avatar]"
    :infinite="true"
    :show-thumbnails="true"
  />
</template>

<script setup>
import { useRoute } from 'vue-router'
import { $message } from '@/utils/message.js'
import { addInformation, uploadImg } from '@/api/common.js'
import { useUserStore } from '@/stores/user/index.js'
import ImagePreview from '@/components/common/ImagePreview/index.vue'
import { ref } from 'vue'

const userStore = useUserStore()
const $route = useRoute()
const previewVisible = ref(false)
const currentIndex = ref(0)
// 编辑模式控制
const editMode = reactive({
  basic: false,
  security: false,
  emergency: false,
  additional: false
})

// 用户信息
const userInfo = reactive({
  type: '',
  begin: '',
  end: '',
  num: '',
  name: '',
  sex: '',
  country: '',
  birthday: '',
  live: '',
  detailed: '',
  nickname: '',
  avatar: '',
  email: '',
  phone: '',
  urgentName: '',
  urgentRelationship: '',
  urgentPhone: '',
  urgentDetailed: '',
  qualification: '',
  bloodType: '',
  industry: '',
  annualSalary: '',
  occupation: '',
  physicalCondition: '',
  runningYear: '',
  weeklyRunning: '',
  monthlyRunning: '',
  firstTimeComplete: '',
  halfHorseDest: '',
  participateFrequency: '',
  runningShoeDrand: '',
  clothingDrand: '',
  watchDrand: '',
  runningApp: '',
  sportsDrink: '',
  userId: ''
})

// 表单数据
const formData = reactive({
  type: '',
  begin: '',
  end: '',
  num: '',
  name: '',
  sex: '',
  country: '',
  birthday: '',
  live: '',
  detailed: '',
  nickname: '',
  avatar: '',
  email: '',
  phone: '',
  urgentName: '',
  urgentRelationship: '',
  urgentPhone: '',
  urgentDetailed: '',
  qualification: '',
  bloodType: '',
  industry: '',
  annualSalary: '',
  occupation: '',
  physicalCondition: '',
  runningYear: '',
  weeklyRunning: '',
  monthlyRunning: '',
  firstTimeComplete: '',
  halfHorseDest: '',
  participateFrequency: '',
  runningShoeDrand: '',
  clothingDrand: '',
  watchDrand: '',
  runningApp: '',
  sportsDrink: '',
  userId: ''
})


// 切换编辑模式
const toggleEdit = (section) => {
  editMode[section] = true
  // 将用户信息复制到表单数据
  Object.keys(formData).forEach(key => {
    formData[key] = userInfo[key]
  })
}

// 取消编辑
const cancelEdit = (section) => {
  editMode[section] = false
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    formData[key] = userInfo[key]
  })
}

// 验证基本信息
const validateBasicInfo = () => {
  const requiredFields = ['nickname', 'country', 'type', 'num', 'name', 'sex', 'begin', 'end', 'birthday', 'live', 'detailed']
  for (let field of requiredFields) {
    if (!formData[field]) {
      $message.error(`请填写${getFieldLabel(field)}`)
      return false
    }
  }
  return true
}

// 验证账户安全信息
const validateSecurityInfo = () => {
  const requiredFields = ['avatar', 'email', 'phone']
  for (let field of requiredFields) {
    if (!formData[field]) {
      $message.error(`请填写${getFieldLabel(field)}`)
      return false
    }
  }
  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(formData.email)) {
    $message.error('请输入正确的邮箱格式')
    return false
  }
  // 手机号格式验证
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.phone)) {
    $message.error('请输入正确的手机号格式')
    return false
  }
  return true
}

// 验证紧急联系人信息
const validateEmergencyInfo = () => {
  const requiredFields = ['urgentName', 'urgentRelationship', 'urgentPhone', 'urgentDetailed']
  for (let field of requiredFields) {
    if (!formData[field]) {
      $message.error(`请填写${getFieldLabel(field)}`)
      return false
    }
  }
  // 紧急联系人电话格式验证
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.urgentPhone)) {
    $message.error('请输入正确的紧急联系人电话格式')
    return false
  }
  return true
}

// 验证更多资料信息
const validateAdditionalInfo = () => {
  const requiredFields = ['qualification', 'bloodType', 'industry', 'annualSalary', 'occupation', 'physicalCondition', 'runningYear', 'weeklyRunning', 'monthlyRunning', 'firstTimeComplete', 'halfHorseDest', 'participateFrequency', 'runningShoeDrand', 'clothingDrand', 'watchDrand', 'runningApp', 'sportsDrink']
  for (let field of requiredFields) {
    if (!formData[field]) {
      $message.error(`请填写${getFieldLabel(field)}`)
      return false
    }
  }
  return true
}
const openPreview = (index) => {
  currentIndex.value = index
  previewVisible.value = true
}
// 保存基本信息
const saveBasicInfo = async () => {
  if (!validateBasicInfo()) return
  await saveAndUpdate()
  editMode.basic = false
}

// 保存账户安全信息
const saveSecurityInfo = async () => {
  if (!validateSecurityInfo()) return
  await saveAndUpdate()
  editMode.security = false

}

// 保存紧急联系人信息
const saveEmergencyInfo = async () => {
  if (!validateEmergencyInfo()) return
  await saveAndUpdate()
  editMode.emergency = false
}

// 保存更多资料信息
const saveAdditionalInfo = async () => {
  // if (!validateAdditionalInfo()) return
  await saveAndUpdate()
  editMode.additional = false
}

const saveAndUpdate = async () => {
  try {
    const res = await addInformation(formData)
    if (res.code == 200) {
      // 更新用户信息
      Object.keys(formData).forEach(key => {
        userInfo[key] = formData[key]
      })
      $message.success('保存成功')
    }
  } catch (error) {
    $message.error('保存失败，请重试')
  }
}
// 修复后的handleAvatarChange函数
const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (file) {
    try {
      // 显示上传状态
      const avatarPreview = document.querySelector('.avatar-preview')
      if (avatarPreview) {
        avatarPreview.classList.add('uploading')
      }

      let uploadFormData = new FormData(); // 重命名避免冲突
      uploadFormData.append('file', file, file.name);

      const res = await uploadImg(uploadFormData)
      console.log(res.data)

      if (res.data.code === 200) {
        // 正确更新响应式数据
        formData.avatar = res.data.url;
        userInfo.avatar = res.data.url;

        $message.success('头像上传成功')

        // 移除上传状态
        if (avatarPreview) {
          avatarPreview.classList.remove('uploading')
          avatarPreview.classList.add('upload-success')
        }
      } else {
        $message.error('上传失败')
        if (avatarPreview) {
          avatarPreview.classList.remove('uploading')
        }
      }
    } catch (error) {
      $message.error('上传失败')
      const avatarPreview = document.querySelector('.avatar-preview')
      if (avatarPreview) {
        avatarPreview.classList.remove('uploading')
      }
    }
  }
}

// 获取证件类型文本
const getIdTypeText = (type) => {
  const typeMap = {
    '1': '身份证',
    '2': '护照'
  }
  return typeMap[type] || '未填写'
}

// 获取性别文本
const getSexText = (sex) => {
  const sexMap = {
    '1': '男',
    '2': '女',
    '3': '未知',
  }
  return sexMap[sex] || '未填写'
}

// 获取字段标签
const getFieldLabel = (field) => {
  const labelMap = {
    nickname: '昵称',
    country: '国家/地区',
    type: '证件类型',
    num: '证件号码',
    name: '姓名',
    sex: '性别',
    begin: '证件有效期开始',
    end: '证件有效期结束',
    birthday: '生日',
    live: '现居省/市区',
    detailed: '详细地址',
    avatar: '头像',
    email: '邮箱',
    phone: '手机号码',
    urgentName: '紧急联系人（姓名）',
    urgentRelationship: '紧急联系人（关系）',
    urgentPhone: '紧急联系人（电话）',
    urgentDetailed: '紧急联系人（详细地址）',
    qualification: '学历',
    bloodType: '血型',
    industry: '行业',
    annualSalary: '年薪',
    occupation: '职业',
    physicalCondition: '身体状况',
    runningYear: '参与跑步年数',
    weeklyRunning: '每周跑步次数',
    monthlyRunning: '每月跑步公里',
    firstTimeComplete: '首次完成全马日期',
    halfHorseDest: '半马个人最好成绩',
    participateFrequency: '参加上马次数',
    runningShoeDrand: '穿着跑鞋品牌',
    clothingDrand: '穿着服装品牌',
    watchDrand: '佩戴运动手表品牌',
    runningApp: '使用跑步软件',
    sportsDrink: '最爱喝运动饮料品牌'
  }
  return labelMap[field] || field
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    await userStore.getUserInfo();
    Object.assign(userInfo, userStore.userInfo.post)
  } catch (error) {
    $message.error('加载用户信息失败')
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  if (userStore.isSign) {
    loadUserInfo()
  }
})
</script>

<style scoped lang="scss">
.mainTitle {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
  border-bottom: 1px solid #cccccc;

  &:first-child {
    padding-top: 0;
  }

  h2 {
    font-size: 20px;
    margin: 0;
  }

  .tips {
    font-size: 12px;
    color: red;
  }

  .edit {
    color: dodgerblue;
    cursor: pointer;
    margin-left: auto;

    &:hover {
      color: #6b46c1;
    }
  }

  .edit-actions {
    margin-left: auto;
    display: flex;
    gap: 10px;

    .save {
      color: #4caf50;
      cursor: pointer;

      &:hover {
        color: #388e3c;
      }
    }

    .cancel {
      color: #f44336;
      cursor: pointer;

      &:hover {
        color: #d32f2f;
      }
    }
  }
}


.info-content {
  padding: 20px 0;

  .info-row {
    display: flex;
    gap: 30px;
    margin-bottom: 15px;

    .info-item {
      flex: 1;
      display: flex;
      align-items: center;

      label {
        font-weight: 500;
        margin-right: 10px;
        min-width: 120px;
        color: #333;
      }

      span {
        color: #666;
      }
    }
  }
}

.form-content {
  padding: 20px 0;

  .form-row {
    display: flex;
    gap: 30px;
    margin-bottom: 20px;

    .form-item {
      flex: 1;

      label {
        display: block;
        font-weight: 500;
        margin-bottom: 8px;
        color: #333;

        .required {
          color: red;
          margin-left: 2px;
        }
      }

      input, select {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        transition: border-color 0.3s ease;

        &:focus {
          outline: none;
          border-color: #1976d2;
          box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.1);
        }

        &::placeholder {
          color: #999;
        }
      }

      input[type="file"] {
        padding: 8px;
      }
    }
  }
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  cursor: pointer;
}
// 响应式设计
@media (max-width: 768px) {
  .user-content {
    flex-direction: column;
    gap: 20px;
  }

  .left-side {
    width: 100%;

    .left-side-item {
      display: inline-block;
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }

  .info-content .info-row,
  .form-content .form-row {
    flex-direction: column;
    gap: 15px;
  }

  .mainTitle {
    flex-wrap: wrap;
    gap: 10px;

    .tips {
      order: 3;
      width: 100%;
    }
  }
}
// 在style部分添加以下样式
.avatar-upload-container {
  .avatar-upload-wrapper {
    position: relative;
    display: inline-block;
  }

  .avatar-preview {
    width: 100px;
    height: 100px;
    border: 2px dashed #ddd;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    background-color: #fafafa;

    &:hover {
      border-color: #1976d2;
      background-color: #f5f5f5;

      .upload-overlay {
        opacity: 1;
      }
    }

    &.has-avatar {
      border-style: solid;
      border-color: #e0e0e0;

      &:hover {
        border-color: #1976d2;
      }
    }

    &.uploading {
      border-color: #1976d2;

      .upload-loading {
        opacity: 1;
      }

      .avatar-image,
      .avatar-placeholder,
      .upload-overlay {
        opacity: 0.3;
      }
    }

    &.upload-success {
      border-color: #4caf50;
      animation: success-pulse 0.6s ease;
    }
  }

  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: opacity 0.3s ease;
  }

  .avatar-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    color: #999;
    font-size: 12px;
    text-align: center;
    transition: opacity 0.3s ease;

    .upload-icon {
      color: #ccc;
    }
  }

  .upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 4px;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: white;
    font-size: 12px;

    .camera-icon {
      color: white;
    }
  }

  .upload-loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #1976d2;
    font-size: 12px;

    .loading-spinner {
      width: 20px;
      height: 20px;
      border: 2px solid #e3f2fd;
      border-top: 2px solid #1976d2;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
  }

  .avatar-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes success-pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}
</style>
